package com.cheyunkeji.er.fragment.evaluate;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.AddCarArchiveActivity;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.activity.evaluate.PhotoPreViewActivity;
import com.cheyunkeji.er.activity.evaluate.SelectCarInfoActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.BeforeArchiveListItem;
import com.cheyunkeji.er.bean.evaluate.CarInfo;
import com.cheyunkeji.er.bean.evaluate.CarTempAttrList;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.bean.evaluate.VehicleInfoBean;
import com.cheyunkeji.er.bean.event.RefreshUIEvent;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.utils.AsciiCodeLimitFilter;
import com.cheyunkeji.er.utils.ImageLoadUtil;
import com.cheyunkeji.er.utils.InputLowerToUpper;
import com.cheyunkeji.er.utils.KeyBoardUtil;
import com.cheyunkeji.er.utils.SerializeUtil;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.evaluate.ImageSelectDialog;
import com.cheyunkeji.er.view.evaluate.TakePhotoDisplayView;
import com.cheyunkeji.er.view.evaluate.wheel_selector.IListPickerOK;
import com.cheyunkeji.er.view.evaluate.wheel_selector.InfoData;
import com.cheyunkeji.er.view.evaluate.wheel_selector.ListPicker;
import com.cheyunkeji.er.view.evaluate.wheel_selector.ListPickerItem;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;
import okhttp3.Call;
import okhttp3.Request;

import static android.app.Activity.RESULT_OK;

/** Created by Michael on 2017/3/24 17:35. */
public class EvaluateBaseInfoFragment extends BaseFragment
    implements IListPickerOK,
        EvaluateWorkflowActivity.OnOutActionListener,
        SDialog.SDialog2Listener,
        TakePhotoDisplayView.OnTakePhotoListener,
        OssService.onImageProcessedResultListener,
        ImageSelectDialog.ImageSelectListener {

  public static final int PAGE_INDEX = 0;
  public static final int CREATE_NEW_CAR_ARCHIVE = 0X123;
  private static final int PARAMS_NOT_NECESSARY = -1;
  private static final String TAG = EvaluateBaseInfoFragment.class.getSimpleName();
  private static final int PREVIEW_IMG_REQUEST = 0x133;
  private static final int REQUEST_CODE_SELECT_CAR_BRAND = 0x124;
  private static final int REQUEST_CODE_SELECT_CAR_SERIES = 0x125;
  private static final int REQUEST_CODE_SELECT_CAR_MODEL = 0x126;
  public Runnable mTask;
  HashMap<String, String> params = new HashMap<>();

  @BindView(R.id.iv_star)
  ImageView ivStar;

  @BindView(R.id.tv_vin_code)
  TextView tvVinCode;

  @BindView(R.id.tv_query_vin)
  TextView tvQueryVin;

  @BindView(R.id.et_vin)
  EditText etVin;

  @BindView(R.id.iv_star1)
  ImageView ivStar1;

  @BindView(R.id.tv_carowner_name_desc)
  TextView tvCarownerNameDesc;

  @BindView(R.id.tv_carowner_name)
  TextView tvCarownerName;

  @BindView(R.id.iv_star2)
  ImageView ivStar2;

  @BindView(R.id.tv_carowner_telenum_desc)
  TextView tvCarownerTelenumDesc;

  @BindView(R.id.tv_carowner_telenum)
  TextView tvCarownerTelenum;

  @BindView(R.id.tv_user_require)
  TextView tvUserRequire;

  @BindView(R.id.ll_user_require)
  LinearLayout llUserRequire;

  @BindView(R.id.tv_user_address)
  TextView tvUserAddress;

  @BindView(R.id.et_contacter)
  EditText etContacter;

  @BindView(R.id.et_contact_telenum)
  EditText etContactTelenum;

  @BindView(R.id.tv_evaluate_method)
  TextView tvEvaluateMethod;

  @BindView(R.id.ll_evaluate_method)
  LinearLayout llEvaluateMethod;

  @BindView(R.id.et_expect_price)
  EditText etExpectPrice;

  @BindView(R.id.tv_expect_brand)
  TextView tvExpectBrand;

  @BindView(R.id.ll_expect_brand)
  LinearLayout llExpectBrand;

  @BindView(R.id.tv_expect_car_series)
  TextView tvExpectCarSeries;

  @BindView(R.id.ll_expect_car_series)
  LinearLayout llExpectCarSeries;

  @BindView(R.id.tv_expect_car_model)
  TextView tvExpectCarModel;

  @BindView(R.id.ll_expect_car_model)
  LinearLayout llExpectCarModel;

  @BindView(R.id.tv_evaluate_code)
  TextView tvEvaluateCode;

  @BindView(R.id.iv_goto_top)
  ImageView ivGotoTop;

  @BindView(R.id.tv_next_step)
  TextView tvNextStep;

  @BindView(R.id.sv_content)
  ScrollView svContent;

  @BindView(R.id.ll_root_view)
  RelativeLayout llRootView;

  @BindView(R.id.tpdv_palate)
  TakePhotoDisplayView tpdvPalate;

  @BindView(R.id.tpdv_drive_license)
  TakePhotoDisplayView tpdvDriveLicense;

  @BindView(R.id.tpdv_vin)
  TakePhotoDisplayView tpdvVin;

  //    当前选中车辆品牌
  private CarInfo.CarBrand selectedCarBrand;
  //    当前选中车型
  private CarInfo.CarModel selectedCarModel;
  //    当前选中车系
  private CarInfo.CarSeries selectedCarSeries;
  private ArrayList<TakePhotoDisplayView> photoViewList;
  private ListPicker listPicker;
  private ArrayList<InfoData> dataList;
  //  字段列表
  private CarTempAttrList attrList;
  private EvaluateDetailResult2 result;
  private ImageSelectDialog imgSelectDialog;

  private String error2Msg = "";
  private VehicleInfoBean error2Data = null;
  private int messageType = -1;
  private Handler uiRefreshHandler =
      new Handler() {

        @Override
        public void handleMessage(Message msg) {
          messageType = msg.what;
          switch (msg.what) {
            case -1: {
              SDialog dialog =
                      new SDialog(
                              EvaluateBaseInfoFragment.this.getActivity(),
                              getString(R.string.t_message_title),
                              getString(R.string.query_no_result),
                              R.string.create_archive,
                              R.string.cancel_close,
                              EvaluateBaseInfoFragment.this,
                              true);
              dialog.setCanceledOnTouchOutside(false);
              dialog.show();
              break;
            }
            case -2: {
              SDialog dialog =
                      new SDialog(
                              EvaluateBaseInfoFragment.this.getActivity(),
                              getString(R.string.t_message_title),
                              error2Msg,
                              R.string.confirm_next,
                              R.string.cancel_close,
                              EvaluateBaseInfoFragment.this,
                              true);
              dialog.setCanceledOnTouchOutside(false);
              dialog.show();
              break;
            }
            default:
              break;
          }
        }
      };
  //    图片上传次数计数器
  private int uploadImgCounter = 0;
  private HashMap<String, String> imgParams;
  private ImageCaptureManager captureManager;

  @Override
  protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
    contentView = inflater.inflate(R.layout.er_frag_evaluate_base_info, container, false);
    ButterKnife.bind(this, contentView);
    EventBus.getDefault().register(this);
  }

  @Override
  protected void init() {

    captureManager = new ImageCaptureManager(getActivity());

    //      反序列化得到字段列表
    attrList = SerializeUtil.getCarTempAttrList();
    dataList = new ArrayList<>();

    if (null == params) {
      params = new HashMap<>();
    }

    result = MyApplication.getInstance().getEvaluateResult();
    if (null != result) {
      displayInfo();
    }
  }

  @Override
  protected void initView() {

    photoViewList = new ArrayList<>(3);
    photoViewList.add(tpdvPalate);
    photoViewList.add(tpdvDriveLicense);
    photoViewList.add(tpdvVin);

    tvQueryVin.setOnClickListener(this);
    llUserRequire.setOnClickListener(this);
    llExpectBrand.setOnClickListener(this);
    llExpectCarSeries.setOnClickListener(this);
    llExpectCarModel.setOnClickListener(this);
    llEvaluateMethod.setOnClickListener(this);

    tpdvDriveLicense.setListener(this);
    tpdvPalate.setListener(this);
    tpdvVin.setListener(this);

    tvNextStep.setOnClickListener(this);
    ivGotoTop.setOnClickListener(this);

    etVin.setFilters(
        new InputFilter[] {
          new InputFilter.LengthFilter(Constants.VIN_CODE_LENGTH), new AsciiCodeLimitFilter()
        });
    etVin.setTransformationMethod(InputLowerToUpper.getInstance());
    listPicker = new ListPicker(EvaluateBaseInfoFragment.this.getActivity(), this, llRootView);

    if (getActivity().getIntent().hasExtra("waitData")) {
      BeforeArchiveListItem beforeArchiveListItem = (BeforeArchiveListItem)(getActivity().getIntent().getSerializableExtra("waitData"));
      if(beforeArchiveListItem!=null){
        etVin.setText(beforeArchiveListItem.getVin());
        tvCarownerName.setText(beforeArchiveListItem.getOwner_realname());
        tvCarownerTelenum.setText(beforeArchiveListItem.getOwner_phone());
        params.put("ownercid", beforeArchiveListItem.getCid());
      }
    }

  }

  @Override
  protected void initData() {}

  @Override
  public void onDestroyView() {
    super.onDestroyView();
    EventBus.getDefault().unregister(this);
  }

  @Override
  public void onClick(View v) {
    super.onClick(v);

    switch (v.getId()) {
      case R.id.tv_query_vin:
        if (TextUtils.isEmpty(etVin.getText().toString())) {
          SToast.show("请输入VIN");
          return;
        }
        if (etVin.getText().toString().length() != 17) {
          SToast.show("请输入正确的VIN");
          return;
        }

        searchByVin(etVin.getText().toString().toUpperCase());

        break;
      case R.id.ll_user_require:
        dataList.clear();
        for (int i = 0; i < attrList.getAr_khxq().size(); i++) {
          dataList.add(new ListPickerItem(i + "", attrList.getAr_khxq().get(i)));
        }

        listPicker.setList(String.valueOf(R.id.ll_user_require), dataList);

        KeyBoardUtil.dismissKeyboard(getActivity());
        listPicker.listPickerDialog();
        break;

      case R.id.ll_evaluate_method:
        dataList.clear();
        for (int i = 0; i < attrList.getAr_pgfs().size(); i++) {
          dataList.add(new ListPickerItem(i + "", attrList.getAr_pgfs().get(i)));
        }

        listPicker.setList(String.valueOf(R.id.ll_evaluate_method), dataList);
        KeyBoardUtil.dismissKeyboard(getActivity());
        listPicker.listPickerDialog();
        break;

      case R.id.ll_expect_brand:
        Intent intent = new Intent(this.getActivity(), SelectCarInfoActivity.class);
        intent.putExtra(Constants.CAR_BRAND_LEVEL_BRAND, 1);
        startActivityForResult(intent, REQUEST_CODE_SELECT_CAR_BRAND);

        break;

      case R.id.ll_expect_car_series:
        if (selectedCarBrand == null) {
          SToast.show("请选择车辆品牌", Gravity.CENTER);
          return;
        }

        Intent intent2 = new Intent(this.getActivity(), SelectCarInfoActivity.class);
        intent2.putExtra(Constants.CAR_BRAND_LEVEL_BRAND, 2);
        intent2.putExtra("pid", selectedCarBrand.getId());
        startActivityForResult(intent2, REQUEST_CODE_SELECT_CAR_SERIES);

        break;

      case R.id.ll_expect_car_model:
        if (selectedCarSeries == null) {
          SToast.show("请选择车系", Gravity.CENTER);
          return;
        }

        Intent intent3 = new Intent(this.getActivity(), SelectCarInfoActivity.class);
        intent3.putExtra(Constants.CAR_BRAND_LEVEL_BRAND, 3);
        intent3.putExtra("pid", selectedCarSeries.getId());
        startActivityForResult(intent3, REQUEST_CODE_SELECT_CAR_MODEL);

        break;

      case R.id.tv_next_step:
        onSaveEvaluateResult(
            new Runnable() {
              @Override
              public void run() {
                goToNextPage();
              }
            });
        break;
      case R.id.iv_goto_top:
        svContent.smoothScrollTo(0, 0);
        break;
      default:
        break;
    }
  }

  /**
   * 根据vin搜索车辆基本信息
   *
   * @param vin
   */
  private void searchByVin(String vin) {
    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("vin", vin);
    Log.e(TAG, "searchByVin:  vin ==================== " + vin);
    ApiClient.postForm(
        HttpConstants.GET_VEHICLE_INFO_BY_VIN,
        params,
        new RespCallback<VehicleInfoBean>() {

          @Override
          protected void onRequestFailed(String msg) {
            SToast.show(msg);
          }

          @Override
          protected void onSuccess(VehicleInfoBean data) {
            if (null != data) {
              fillData(data);
            }
          }

          @Override
          protected void onCodeNegative_1() {
            Log.e(TAG, "onCodeNegative_1: " + "code is -1 ");
            //              code为 -1，未查询到数据
            uiRefreshHandler.sendEmptyMessage(-1);
          }
          @Override
          protected void onCodeNegative_2(JSONObject obj) {

            try {
              error2Msg = obj.getString("msg");
              error2Data = (new GsonBuilder()).create().fromJson(obj.getString("data"),VehicleInfoBean.class);
              uiRefreshHandler.sendEmptyMessage(-2);
            } catch (JSONException e) {

            }
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }
        });
  }

  /**
   * 将vin查询匹配返回的数据显示到界面上
   *
   * @param data
   */
  private void fillData(VehicleInfoBean data) {
    if (null != data.getCustomer() && !TextUtils.isEmpty(data.getCustomer().getRealname())) {
      tvCarownerName.setText(data.getCustomer().getRealname());
    }
    if (null != data.getCustomer() && !TextUtils.isEmpty(data.getCustomer().getPhone())) {
      tvCarownerTelenum.setText(data.getCustomer().getPhone());
    }
    if (null != data.getCustomer() && !TextUtils.isEmpty(data.getCustomer().getAddress())) {
      tvUserAddress.setText(data.getCustomer().getAddress());
    }
    params.put("vid", data.getVid());
    params.put("ownercid", data.getOwnercid());
    //      通知第二页刷新显示车辆档案相关数据
    EventBus.getDefault().post(data);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
      case PhotoPicker.REQUEST_CODE:
        if (data != null) {
          String localImgPath =
              data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
          if (!TextUtils.isEmpty(localImgPath)) {

            photoViewList.get((int) llRootView.getTag()).setImgPath(localImgPath);
            photoViewList.get((int) llRootView.getTag()).setPhotoBtnState(true);
            ImageLoadUtil.loadImgInFrag(
                this, localImgPath, photoViewList.get((int) llRootView.getTag()).getImageView());
          }
        }
        break;

        //            VIN搜索后返回vin码，然后进行查询
      case CREATE_NEW_CAR_ARCHIVE:
        if (null != data && data.getBooleanExtra("CREATE_ARCHIVE_OK", false)) {

          searchByVin(etVin.getText().toString().toUpperCase());
        }

        break;

        //           删除照片
      case PREVIEW_IMG_REQUEST:
        if (data == null) {
          return;
        }

        boolean deleteImg = data.getBooleanExtra("DELETE_IMG", false);
        Log.e(TAG, "onActivityResult: " + deleteImg);

        if (deleteImg) {

          photoViewList.get((int) llRootView.getTag()).setImgPath("");
          photoViewList.get((int) llRootView.getTag()).setPhotoBtnState(false);
          photoViewList.get((int) llRootView.getTag()).getImageView().setImageDrawable(null);
        }
        break;

      case REQUEST_CODE_SELECT_CAR_BRAND:
        if (null != data && null != data.getSerializableExtra("CAR_BRAND")) {
          selectedCarBrand = (CarInfo.CarBrand) data.getSerializableExtra("CAR_BRAND");
          tvExpectBrand.setText(selectedCarBrand.getTitle());
          tvExpectCarSeries.setText("");
          tvExpectCarModel.setText("");
          selectedCarSeries = null;
          selectedCarModel = null;
        }

        break;

      case REQUEST_CODE_SELECT_CAR_SERIES:
        if (null != data && null != data.getSerializableExtra("CAR_SERIES")) {
          selectedCarSeries = (CarInfo.CarSeries) data.getSerializableExtra("CAR_SERIES");
          tvExpectCarSeries.setText(selectedCarSeries.getTitle());
          tvExpectCarModel.setText("");
          selectedCarModel = null;
        }

        break;

      case REQUEST_CODE_SELECT_CAR_MODEL:
        if (null != data && null != data.getSerializableExtra("CAR_MODEL")) {
          selectedCarModel = (CarInfo.CarModel) data.getSerializableExtra("CAR_MODEL");
          tvExpectCarModel.setText(selectedCarModel.getTitle());
        }

        break;

      case ImageCaptureManager.REQUEST_TAKE_PHOTO:
        if (resultCode == RESULT_OK) {
          captureManager.galleryAddPic();

          String path = captureManager.getCurrentPhotoPath();

          photoViewList.get((int) llRootView.getTag()).setImgPath(path);
          photoViewList.get((int) llRootView.getTag()).setPhotoBtnState(true);
          ImageLoadUtil.loadImgInFrag(
              this, path, photoViewList.get((int) llRootView.getTag()).getImageView());
        }

        break;

      default:
        break;
    }
  }

  /** 进入图片选择页面 */
  private void pickPhoto() {
    PhotoPicker.builder().setPhotoCount(1).start(getActivity(), EvaluateBaseInfoFragment.this);
  }

  @Override
  public void onListOK(String tag, InfoData infoData) {

    switch (tag) {
      case R.id.ll_user_require + "":
        tvUserRequire.setText(infoData.getTitle());
        break;

      case R.id.ll_evaluate_method + "":
        tvEvaluateMethod.setText(infoData.getTitle());
        break;

      default:
        break;
    }
  }

  /**
   * 获取车辆品牌信息
   *
   * @param level
   * @param pid
   * @param callBack
   */
  public void loadCarInfo(int level, int pid, RespCallback callBack) {

    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    if (level != PARAMS_NOT_NECESSARY) params.put("level", String.valueOf(level));
    if (pid != PARAMS_NOT_NECESSARY) params.put("pid", String.valueOf(pid));
    ApiClient.postForm(HttpConstants.GET_CAR_BRAND_LIST, params, callBack);
  }

  @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
  public void onMessageEvent(RefreshUIEvent event) {

    Log.e(TAG, "onMessageEvent: EventType : " + event.getEventType());

    if (event.getEventType() == RefreshUIEvent.TYPE_REFRESH_EVAL_RESULT) {

      if (null != MyApplication.getInstance().getEvaluateResult()) {
        result = MyApplication.getInstance().getEvaluateResult();
        displayInfo();
        Log.e(TAG, "onMessageEvent: msg received ");
      }

    } else if (event.getEventType() == RefreshUIEvent.TYPE_REFRESH_FILL_VIN) {

      Log.e(TAG, "onMessageEvent: " + event.message);
      etVin.setText(event.message);
    }

    //       接收并使用完Sticky消息后移除，避免再次进入界面时重复接收
    EventBus.getDefault().removeStickyEvent(event);
  }

  @Override
  public void onSaveEvaluateResult(Runnable task) {

    if (task != null) this.mTask = task;

    for (int i = 0; i < photoViewList.size(); i++) {
      if (!TextUtils.isEmpty(photoViewList.get(i).getImagePath())
          && !photoViewList.get(i).getImagePath().startsWith("http")) {
        showDialog();
        uploadImgToOss();
        return; // 只要至少选择过一张图片，就直接return调用uploadImgToOss方法进行上传图片，否则没有选择照片，直接上传其他数据
      }
    }
    saveData();
  }

  /** OSS图片上传 */
  private void uploadImgToOss() {

    for (int i = 0; i < photoViewList.size(); i++) {

      if (!TextUtils.isEmpty(photoViewList.get(i).getImagePath())
          && !photoViewList.get(i).getImagePath().startsWith("http")) {
        MyApplication.getInstance()
            .getOssService(EvaluateBaseInfoFragment.this)
            .asyncPutImage(
                OssService.getOssObjectInfo(true),
                photoViewList.get(i).getImagePath(),
                String.valueOf(photoViewList.get(i).getItemIndex()));
        ++uploadImgCounter;
      }
    }
  }

  //    图片上传成功回调
  @Override
  public void onUploadOk(String imgUrl, Object tag) {

    --uploadImgCounter;
    Log.e(
        TAG,
        "onUploadOk    imgUrl : "
            + imgUrl
            + " || tag : "
            + tag
            + "  uploadImageCounter : "
            + uploadImgCounter);

    if (!TextUtils.isEmpty(imgUrl)) {
      photoViewList.get(Integer.valueOf((String) tag)).setImgPath(imgUrl);
    }
    if (uploadImgCounter == 0) {

      saveData();
    }
  }

  private void saveData() {

    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());

    //        if (!TextUtils.isEmpty(etVin.getText().toString()))
    params.put("vin", etVin.getText().toString().toUpperCase());

    params.put("conname", etContacter.getText().toString());
    params.put("conphone", etContactTelenum.getText().toString());

    params.put("khqwsj", etExpectPrice.getText().toString());

    if (!TextUtils.isEmpty(tvEvaluateMethod.getText().toString())
        && attrList.getAr_pgfs().indexOf(tvEvaluateMethod.getText().toString()) != -1) {
      params.put(
          "pgfs",
          String.valueOf(attrList.getAr_pgfs().indexOf(tvEvaluateMethod.getText().toString())));
    }

    if (!TextUtils.isEmpty(tvUserRequire.getText().toString())
        && -1 != attrList.getAr_khxq().indexOf(tvUserRequire.getText().toString())) {
      params.put(
          "khxq",
          String.valueOf(attrList.getAr_khxq().indexOf(tvUserRequire.getText().toString())));
    }

    if (null != selectedCarBrand) params.put("ibrand", selectedCarBrand.getId());
    if (null != selectedCarSeries) params.put("iseries", selectedCarSeries.getId());
    if (null != selectedCarModel) params.put("ispec", selectedCarModel.getId());

    if (null != getActivity().getIntent().getStringExtra("AID")) {
      params.put("aid", getActivity().getIntent().getStringExtra("AID"));
    }
    if (null != getActivity().getIntent().getStringExtra("thid")) {
      params.put("thid", getActivity().getIntent().getStringExtra("thid"));
    }

    Log.e(TAG, "saveData 已上传待编辑 AID : " + getActivity().getIntent().getStringExtra("AID"));

    if (imgParams == null) {
      imgParams = new HashMap<>();
    }

    imgParams.put("vinzp", tpdvVin.getImagePath());
    imgParams.put("cpzp", tpdvPalate.getImagePath());
    imgParams.put("xszzp", tpdvDriveLicense.getImagePath());
    params.put("image", new Gson().toJson(imgParams));

    if (MyApplication.getInstance().getEvaluateResult() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
      int[] iroute = new int[15];
      iroute[EvaluateBaseInfoFragment.PAGE_INDEX] = 1;
      String json = new Gson().toJson(iroute);
      Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
      params.put("iroute", json.substring(1, json.length() - 1));
    } else {
      MyApplication.getInstance()
          .getEvaluateResult()
          .getIroute()
          .set(EvaluateBaseInfoFragment.PAGE_INDEX, 1);
      String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
      params.put("iroute", json.substring(1, json.length() - 1));
      Log.e(
          TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
    }

    Log.e(
        TAG,
        "saveData: upload data URL : "
            + ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL());

    for (String key : params.keySet()) {
      Log.e(TAG, "saveData: " + "key : " + key + "  value : " + params.get(key));
    }

    Log.e(
        TAG,
        "saveData: 当前文件保存路径 ： "
            + ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL());

    //        根据评估类型进行保存或编辑
    int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();

    //       保存新创建、未上传待评估数据
    if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {

      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new RespCallback<EvaluateDetailResult2>() {

            @Override
            protected void onRequestFailed(String msg) {

              SToast.show(msg);
              if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                mTask.run();
                mTask = null;
              }
            }

            @Override
            protected void onSuccess(EvaluateDetailResult2 data) {

              if (null != data) {

                MyApplication.getInstance().setEvaluateResult(data);

                Log.e(TAG, "onSuccess: 第一步保存成功结果 ：  " + new Gson().toJson(data));
                //                        SToast.show("保存成功");

                //                    如果保存完成后不跳转，则重新赋值result
                result = data;

                if (mTask != null) {
                  mTask.run();
                  mTask = null;
                }
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              showDialog();
            }

            @Override
            public void onAfter(int id) {
              dismissDialog();
            }
          });

      //            保存已上传待编辑数据，接口换为updateArchiveInfo
    } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {

      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
              // 网络异常
              if (e instanceof UnknownHostException || e instanceof SocketException) {
                SToast.show(R.string.tip_network_error, Gravity.CENTER);
                return;
              }
            }

            @Override
            public void onResponse(String response, int id) {

              try {

                JSONObject obj = new JSONObject(response);
                if (obj.optInt("code") == 1) {
                  //                            SToast.show("保存成功", Gravity.CENTER);

                  Log.e(TAG, "onResponse: 编辑成功 : " + obj.optString("data"));

                  if (mTask != null) {
                    Log.e(TAG, "onSuccess: Task 任务执行");
                    mTask.run();
                    mTask = null;
                  }

                } else {
                  SToast.show(obj.optString("msg"));

                  if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                    mTask.run();
                    mTask = null;
                  }
                }
              } catch (JSONException e) {
                e.printStackTrace();
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              showDialog();
            }

            @Override
            public void onAfter(int id) {
              dismissDialog();
            }
          });
    }
  }

  private void goToNextPage() {
    ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(CarBaseInfoFragment.PAGE_INDEX);
  }

  @Override
  public void onUploadFailed() {
    SToast.show("图片上传失败");
  }

  @Override
  public void onResume() {
    super.onResume();
  }

  private void displayInfo() {

    if (!TextUtils.isEmpty(result.getIbrand_name()) && !TextUtils.isEmpty(result.getIbrand())) {
      selectedCarBrand = new CarInfo.CarBrand(result.getIbrand(), result.getIbrand_name(), "");
    }

    if (!TextUtils.isEmpty(result.getIseries()) && !TextUtils.isEmpty(result.getIseries_name())) {
      selectedCarSeries = new CarInfo.CarSeries(result.getIseries(), result.getIseries_name());
    }

    if (!TextUtils.isEmpty(result.getIspec()) && !TextUtils.isEmpty(result.getIspec_name())) {
      selectedCarModel = new CarInfo.CarModel(result.getIspec(), result.getIspec_name());
    }

    if (!TextUtils.isEmpty(result.getVin())) {
      etVin.setText(result.getVin());
    }

    if (result.getCustomer() != null && !TextUtils.isEmpty(result.getCustomer().getRealname())) {
      tvCarownerName.setText(result.getCustomer().getRealname());
    }

    if (null != result.getCustomer() && !TextUtils.isEmpty(result.getCustomer().getPhone())) {
      tvCarownerTelenum.setText(result.getCustomer().getPhone());
    }

    if (!TextUtils.isEmpty(result.getKhxq())) {
      tvUserRequire.setText(attrList.getAr_khxq().get(Integer.valueOf(result.getKhxq())));
    }

    //        客户地址
    if (null != result.getCustomer() && !TextUtils.isEmpty(result.getCustomer().getAddress())) {
      tvUserAddress.setText(result.getCustomer().getAddress());
    }

    if (!TextUtils.isEmpty(result.getConname())) {
      etContacter.setText(result.getConname());
    }

    if (!TextUtils.isEmpty(result.getConphone())) {
      etContactTelenum.setText(result.getConphone());
    }

    if (!TextUtils.isEmpty(result.getPgfs())) {
      tvEvaluateMethod.setText(attrList.getAr_pgfs().get(Integer.valueOf(result.getPgfs())));
    }

    if (!TextUtils.isEmpty(result.getKhqwsj()) && Float.valueOf(result.getKhqwsj()) != 0) {
      etExpectPrice.setText(result.getKhqwsj());
    }

    if (!TextUtils.isEmpty(result.getIbrand_name())) {
      tvExpectBrand.setText(result.getIbrand_name());
    }

    if (!TextUtils.isEmpty(result.getIseries_name())) {
      tvExpectCarSeries.setText(result.getIseries_name());
    }

    if (!TextUtils.isEmpty(result.getIspec_name())) {
      tvExpectCarModel.setText(result.getIspec_name());
    }

    if (!TextUtils.isEmpty(result.getAfid())) {
      tvEvaluateCode.setText(result.getAfid());
    }

    //       展示图片
    if (null != result.getImage()) {

      if (!TextUtils.isEmpty(result.getImage().getCpzp())) {
        ImageLoadUtil.loadImgInFrag(this, result.getImage().getCpzp(), tpdvPalate.getImageView());
        tpdvPalate.setImgPath(result.getImage().getCpzp());
        tpdvPalate.setPhotoBtnState(true);
      }

      if (!TextUtils.isEmpty(result.getImage().getXszzp())) {
        ImageLoadUtil.loadImgInFrag(
            this, result.getImage().getXszzp(), tpdvDriveLicense.getImageView());
        tpdvDriveLicense.setImgPath(result.getImage().getXszzp());
        tpdvDriveLicense.setPhotoBtnState(true);
      }

      if (!TextUtils.isEmpty(result.getImage().getVinzp())) {
        ImageLoadUtil.loadImgInFrag(this, result.getImage().getVinzp(), tpdvVin.getImageView());
        tpdvVin.setImgPath(result.getImage().getVinzp());
        tpdvVin.setPhotoBtnState(true);
      }
    }
  }

  @Override
  public void onClick(boolean l, View view) {
    if (l) {
      if (messageType == -2) {
        if(error2Data!=null) {
          fillData(error2Data);
        }
      }
      else{
        //新增档案
        Intent intent = new Intent(getActivity(), AddCarArchiveActivity.class);
        intent.putExtra("VIN", etVin.getText().toString().toUpperCase());
        if (getActivity().getIntent().hasExtra("waitData")) {
          BeforeArchiveListItem beforeArchiveListItem = (BeforeArchiveListItem) (getActivity().getIntent().getSerializableExtra("waitData"));
          intent.putExtra("waitData", beforeArchiveListItem);
        }
        startActivityForResult(intent, CREATE_NEW_CAR_ARCHIVE);
      }
    }
  }

  @Override
  public void takePhoto(int itemIndex) {
    llRootView.setTag(itemIndex);
    if (!TextUtils.isEmpty(photoViewList.get(itemIndex).getImagePath())) {
      //          有照片，预览照片
      Intent intent = new Intent(getActivity(), PhotoPreViewActivity.class);
      intent.putExtra("IMG_PATH", photoViewList.get(itemIndex).getImagePath());
      this.startActivityForResult(intent, PREVIEW_IMG_REQUEST);
    } else {
      showImgSelectDialog(photoViewList.get(itemIndex).getTextDesc());
    }
  }

  public void showImgSelectDialog(String titleStr) {
    if (null == imgSelectDialog) {
      imgSelectDialog = new ImageSelectDialog(this.getActivity(), this, titleStr);
    } else {
      imgSelectDialog.setTitleStr(titleStr);
    }
    imgSelectDialog.show();
  }

  private void openSystemCamera() {
    Intent intent = null;
    try {
      intent = captureManager.dispatchTakePictureIntent();
      startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onTakePhotoWithSystemCamera() {
    openSystemCamera();
  }

  @Override
  public void onSelectImgOnGallery() {
    pickPhoto();
  }
}
